package cn.com.pansky.comm.interceptor;

import java.io.UnsupportedEncodingException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import net.vsame.url2sql.helper.Url2SqlContext;
import net.vsame.url2sql.helper.WebHelper;
import net.vsame.url2sql.url.Interceptor;
import net.vsame.url2sql.url.impl.UrlMapping;
import net.vsame.url2sql.url.impl.UrlMapping.Chain;

public class EncoderInterceptor implements Interceptor {

	@Override
	public void init(UrlMapping urlMapping, ServletContext servletContext) {
	}

	@Override
	public void invoke(Chain chain) {
		Url2SqlContext context = WebHelper.getContext();
		String encoder = context.getParam("_charset");
		HttpServletRequest request = context.getRequest();
		try {
			request.setCharacterEncoding("UTF-8");
			if (encoder != null && !encoder.isEmpty()
					&& !encoder.toLowerCase().equals("utf-8")) {
				request.setCharacterEncoding(encoder);
				context.setRequest(request);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		chain.next();
	}

	@Override
	public void destroy() {
	}

}